<?php

?>

<div class="span7" style="margin-bottom: 10px;">
    <button id="reasonListAddItem" class="btn btn-success pull-right" type="button"><i class="icon-plus icon-white"></i> Добавить/изменить </button>
    <h2>Редактирование данных</h2>
</div>


<div class="well span7">
    <form class="form-inline" action="#" method="POST" name="reasonListForm" id="reasonListForm">
        <fieldset>
            <legend>Поиск существующих записей</legend>
            <input type="hidden" name="action" value="<?php echo ACTIONS::REASON_LIST; ?>"> 

            <div class="control-group">
                <p>Интервал времени:</p>
                <label class="control-label" for="from_date">
                    с 
                    <input type="text" class="input-medium" id="reasonListFromDate" name="from_date" value="<?php echo Arr::getValue($params, 'from_date', ''); ?>"> 
                </label>
                &nbsp;&nbsp;&nbsp;
                <label class="control-label" for="to_date"> 
                    по 
                    <input type="text" class="input-medium" id="reasonListToDate" name="to_date" value="<?php echo Arr::getValue($params, 'to_date', ''); ?>"> 
                    <button id="reasonListToDateToday" class="btn btn-info" type="button"><i class="icon-calendar icon-white"></i> Сегодня </button>
                </label>


            </div>

            <div class="control-group">
                <label class="control-label" for="trc_id">Отображение: 
                    <select id="reasonListViewId" name="trc_id" class="input-large">
                    <?php
                        $views = Arr::getValue($params, 'visviews', array());
                        $views[0] = array('id'=>0, 'obj_name'=>'Выберите отображение', 'obj_type'=>0);

                        $selvalue = Arr::getValue($params, 'trc_id', 0);

                        foreach ($views as $row) {
                            $key = Arr::getValue($row, 'id', 0);
                            $val = Arr::getValue($row, 'obj_name', '???');

                            $sel = ($key == $selvalue)? 'selected="selected"' : '';
                            echo '<option value="'.$key.'" '.$sel.'>'.$val."</option>\n";
                        }
                    ?>
                    </select>
                </label>
            </div>

            <div class="control-group">
                <div class="pull-right noWrap">
                    <img src="img/loader.gif" width="32" height="32" id="reasonListFormProcess" style="visibility:hidden;">
                    <button class="btn btn-primary" id="reasonListFormSubmit"><i class="icon-ok-sign icon-white"></i> Показать</button>
                </div>
            </div>
            
        </fieldset>
    </form>
</div>



<ul class="span7 thumbnails" id="reasonListFound" style="margin-left: 30px;"></ul>




<div class="hidden" id="reasonListTemplates">
    
    <ul id="reasonListItem-tmpl" class="hidden">
        <li id="reasonListItem-{%id%}" class="span3 thumbnail noDataCell objCell objtype_{%type%}" style="margin-left: 12px;" onclick="return reasonListItemClick(this);">
            <span class="cell-date" >{%to_date%}</span>
            <div class="cell-name">{%obj_name%}</div>
            <div class="objCell-reason">{%reason_text%}</div>
        </li>
        <?php // type: 2=red 1=blue 0=green  ?>
    </ul>
    
    
</div>
<?php 
    echo includeFile(APP_PAGE_PARTS.'forms/form_view_and_date.php'); 
    echo includeFile(APP_PAGE_PARTS.'forms/form_add_reason.php'); 
?>


<script type="text/javascript">
    
    
    function reasonListGet() {
        Elm.reasonListFound.empty();
        var send = Elm.reasonListForm.serialize();
        reasonListFormDisable();
             
        jsonRequest(
            'reasons.php',
            send,
            function(data) {
                reasonListFormEnable();
                if(!checkSession(data)) {
                    Elm.loginFormModal.dialog('open');
                    Elm.loginFormModal.successCallback = function(){ reasonListGet(); };
                    return;
                }

                if (!data.state) {
                    uiAlert(data.message,'Error');
                    return;
                }

                if (data.hasOwnProperty('response_data')) {
                    var rdata = data.response_data;
                    
                    if (rdata.hasOwnProperty('items')) {
                        Elm.reasonListCurrentItems = rdata.items.byId;
                        reasonListFillFound(rdata.items.sorted);
                        return;
                    }
                }
                
                Elm.reasonListFound.html('Невозможно отобразить полученные данные');
            },

            function() {
                uiAlert('Ошибка соединения','Error');
                reasonListFormEnable();
            }
        );
        
    }
    
    function reasonListFormDisable() {
        Elm.reasonListForm.find('input, button, select').attr('disabled','disabled');
        $('#reasonListFormProcess').css({visibility: 'visible'});
    }
    
    
    function reasonListFormEnable() {
        Elm.reasonListForm.find('input, button, select').removeAttr('disabled');
        $('#reasonListFormProcess').css({visibility: 'hidden'});
    }
    
    
    function reasonListFillFound(itemList) {
        itemList = itemList || {};
        var i,item, html;
        var tmpl = $('#reasonListItem-tmpl');
        var found = '';

        for (i in itemList) {
            if (!itemList.hasOwnProperty(i)) continue;
            item = reasonListFormatItem(itemList[i]);
            
            html = fillTemplate(tmpl, item);
            found += html;
        }
        if (found) Elm.reasonListFound.html(found);
        else Elm.reasonListFound.html('Ничего не найдено');
    }
    
    
    
    function reasonListFormatItem(item) {
        if (item.manual_value) {
            item.type = 0;
            item.reason_text = item.manual_value;
        }
        else if (item.reason) {
            item.type = 1;
            item.reason_text = item.reason;
        }
        else {
            item.type = 2;
            item.reason_text = 'Не заполнено?';
        }
        return item;
    }
    
    
    function reasonListSearchItem(data) {
        var send = {
            to_date: data.date,
            trc_id: data.view,
            action: '<?php echo ACTIONS::REASON_SEARCH; ?>'
        }
        
        jsonRequest(
            'reasons.php',
            send,
            function(data) {
                if(!checkSession(data)) {
                    Elm.loginFormModal.dialog('open');
                    Elm.loginFormModal.successCallback = function(){ reasonListSearchItem(data); };
                    return;
                }

                if (!data.state) {
                    uiAlert(data.message,'Error');
                    return;
                }
                
                var resp = arrayGetValue(data, 'response_data', false);
                var item = arrayGetValue(resp, 'item', false);
                
                if (item) {
                    addReasonDialogOpen(
                        item, 
                        function(formData){ 
                            reasonListRequestReason(
                                formData, 
                                function(){
                                    reasonListItemUpdate(reasonListFormatItem(formData));
                                }
                            ); 
                        }, 
                        function(){}, // onCancel addReason
                        function(){// onDelete addReason
                           reasonListItemDelete(item);
                        }  
                    );
                    return;
                }
                
                uiAlert('Невозможно отобразить полученные данные');
            },

            function() {
                uiAlert('Ошибка соединения','Error');
            }
        );
    }
    
    
    function reasonListItemDelete(item) {
        item = item || {id:0};
        $('#reasonListItem-'+item.id).hide(300, function(){ $(this).remove(); });
    }
    
    function reasonListItemUpdate(item) {
        item = item || {id:0};
        if (!item.id) return;
        var elm = $('#reasonListItem-'+item.id);
        if (!elm) return;
        Elm.reasonListCurrentItems[item.id] = item;
        var newElm = fillTemplate('#reasonListItem-tmpl', item);
        
        elm.before(newElm).remove();
    }
    
    
    function reasonListRequestReason(formData, callback) {
        jsonRequest(
            'reasons.php',
            formData,
            function(data) {
                if(!checkSession(data)) {
                    Elm.loginFormModal.dialog('open');
                    Elm.loginFormModal.successCallback = function(){ reasonListRequestReason(formData); };
                    return;
                }

                if (!data.state) {
                    uiAlert(data.message,'Error');
                    return;
                }
                addReasonDialogClose();
                uiAlert('Изменения сохранены','Информация');
                if (typeof(callback) == 'function') callback();
            },

            function() {
                uiAlert('Ошибка соединения','Error');
            }
        );
    }
    
    
    function reasonListItemEdit(item) {
        addReasonDialogOpen(
            item, 
            function(formData){ 
                reasonListRequestReason(
                    formData, 
                    function(){
                        reasonListItemUpdate(reasonListFormatItem(formData));
                    }
                ); 
            }, 
            
            function(){}, // onCancel addReason
            
            function(){// onDelete addReason
                reasonListItemDelete(item);
            }  
        );
    }
    
    function reasonListItemClick(elm) {
        elm = elm || {id:0};
        var id = elm.id.gReplace('reasonListItem-','');
        if (!id || !Elm.reasonListCurrentItems.hasOwnProperty(id)) return false;
        
        reasonListItemEdit(Elm.reasonListCurrentItems[id]);
        return false;
    }
    
    
    
    
$(function() {
    Elm.reasonListFromDate = $('#reasonListFromDate');
    Elm.reasonListToDate = $('#reasonListToDate');
    Elm.reasonListForm = $('#reasonListForm');
    
    Elm.reasonListFound = $('#reasonListFound');
    Elm.reasonListCurrentItems = {};

    //$.datepicker.setDefaults($.datepicker.regional['ru']);

    
    Elm.reasonListFromDate.datepicker({
        dateFormat  : "yy-mm-dd",
        currentText : "Сегодня",
        closeText   : "Закрыть",
        showButtonPanel: false,
        changeYear  : true,
        changeMonth : true
    });

    Elm.reasonListToDate.datepicker({
        dateFormat  : "yy-mm-dd",
        currentText : "Сегодня",
        closeText   : "Закрыть",
        showButtonPanel: false,
        changeYear  : true,
        changeMonth : true
    });
    
    $('#reasonListToDateToday').click(function(){ Elm.reasonListToDate.datepicker( "setDate" , '0' ); });

    $('#reasonListFormSubmit').click(function(){
        reasonListGet();
        return false;
    });

    $('#reasonListAddItem').click(function(){
        vadDialogOpen(
            {}, 
            function(data) { // onSave
                reasonListSearchItem(data);
            }, 
            function() {} // onCancel vad
        );
        return false;
    });
});



</script>



